/* 
 * Created by linzheyan at 2011-11-29 
 * Copyright HiSupplier.com 
 */

package com.qnvip.sbd.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author linzheyan
 *
 * 2011-11-29
 */
public class JdbcUtil {

	private static Log log = LogFactory.getLog(JdbcUtil.class);
	
	public synchronized static Connection getConnection() throws SQLException {
		Connection connect = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = PropertiesUtil.getString("database.url");
			String user = PropertiesUtil.getString("database.user");
			String password = PropertiesUtil.getString("database.password");
			connect = DriverManager.getConnection(url, user, password);
			connect.setAutoCommit(false);
		} catch (SQLException e) {
			log.error("建立数据库连接出错： " + e.getMessage(), e);
			throw e;
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage(), e);
		}
		return connect;
	}
	
	
	public synchronized static Connection getConnection(String url, String user, String password) throws SQLException {
		Connection connect = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection(url, user, password);
			connect.setAutoCommit(false);
		} catch (SQLException e) {
			log.error("建立数据库连接出错： " + e.getMessage(), e);
			throw e;
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage(), e);
		}
		return connect;
	}
	
	
	public static void close(Connection conn) {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				log.error("数据连接关闭出错", e);
			}
	}
	
	public static void closePreparedStatement(PreparedStatement ps) {
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				log.error("PreparedStatement关闭出错", e);
			}
		}
	}
	
	public static void jdbcRollback(Connection conn){
		try {
			if (conn != null)
				conn.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}
}
